package org.ricks.action.rpc;

import org.ricks.net.MessageProcessor;
import org.ricks.net.StateMachineEnum;
import org.ricks.net.action.ActionBus;
import org.ricks.net.action.context.FlowContext;
import org.ricks.net.action.rpc.RpcClient;
import org.ricks.net.action.context.head.RpcHeadMeta;
import org.ricks.net.action.rpc.RpcSessionManager;
import org.ricks.net.transport.AioSession;

public class RpcHandler implements MessageProcessor<FlowContext<RpcHeadMeta>> {


    @Override
    public void process(AioSession session, FlowContext<RpcHeadMeta> msg) {
        RpcHeadMeta headMeta = msg.headMeta;
        if (!headMeta.isRpcResponse()) {
            ActionBus.handlerAction(session.hashCode(), msg);
        } else {
            RpcClient client = RpcSessionManager.getOrCreateClient(session);
            if (client != null) {
                client.handleRpcResponse(msg);
            }
        }
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum state, Throwable error) {
        if (state == StateMachineEnum.SESSION_CLOSED) {
            RpcSessionManager.onSessionClosed(session);
        }
    }
}
